<?php

namespace addons\facrm\library;

use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class Helper
{
    /**
     * 获取参数字段
     * @param string $types types：customer，contacts
     * @param array $field 查询字段
     * @param array $extend 追加字段
     */
    public static function getfield($types = "customer", $field = '*', $extend = array(), $ignore_column = array())
    {
        $prefix = \think\Config::get('database.prefix');
        $table = "";
        switch ($types) {
            case "contacts":
                $table = "{$prefix}facrm_customer_" . $types;
                break;
            case "contract":
            case "business":
            case "customer":
            case "clues":
            case "contract_receivables":
                $table = "{$prefix}facrm_{$types}";
                break;

            default:

        }
        $dbname = \config('database.database');
        //从数据库中获取表字段信息
        $sql = "SELECT * FROM `information_schema`.`columns` WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?  ORDER BY ORDINAL_POSITION";
        //加载主表的列
        $columnList = Db::query($sql, [$dbname, $table]);

        if ($field!="*"){
            $field=explode(',', $field);
        }

        foreach ($columnList as $index => $item) {
            if (in_array($item['COLUMN_NAME'], $ignore_column)) {
                continue;
            }
            if (is_array($field)&&!in_array($item['COLUMN_NAME'], $field)){
                continue;
            }
            $fieldlist[$item['COLUMN_NAME']] = $item['COLUMN_COMMENT'];
        }

        return array_merge($extend, $fieldlist);
    }


    /**
     * 根据规则自动生成编码
     * @param $prefix
     * @return int|mixed|string
     */
    public static function autoNo($prefix){
        $replace_data=['Y'=>date('Y'),'m'=>date('m'),'d'=>date('d'),'h'=>date("H"),'i'=>date("i"),'s'=>date("s"),'rand'=>rand(100000,999999)];
        return $prefix?__($prefix, $replace_data):'';
    }


    /**
     * 添加默认角色组
     * @param $name
     */
    public static function defaultgroup($name){

        $defaultgroup=ADDON_PATH . $name . DS . 'config' . DS . "defaultgroup.php";
        if (is_file($defaultgroup)) {
            $defaultgroup = include $defaultgroup;

            if($defaultgroup&&isset($defaultgroup['groupList'])){
                try {
                    $olld_new_pid=array();//pid旧新集合

                    foreach ($defaultgroup['groupList'] as $group){

                        //查询rule
                        $rulesids= \app\admin\model\AuthRule::where('name','in',$group['rules'])->column('id');

                        //判断是否存在。判断条件（createtime和name）,存在只更新权限
                        $hasGroup=\app\admin\model\AuthGroup::where('createtime',$group['createtime'])->where('name',$group['name'])->find();

                        if($hasGroup){
                            $hasGroup->rules=implode(',',$rulesids);
                            $hasGroup->save();
                            continue;
                        }
                        //获取父级
                        if ($group['pid']){
                            if (isset($olld_new_pid[$group['pid']])){
                                $group['pid']=$olld_new_pid[$group['pid']];
                            }else if (!\app\admin\model\AuthGroup::where('id',$group['pid'])->count()) {
                                unset($group['pid']);//防止看不到
                            }

                        }
                        $olld_id=$group['id'];
                        if ( isset($group['id']))
                            unset($group['id']);
                        //添加数据
                        $group['rules']=implode(',',$rulesids);
                        $olld_new_pid[$olld_id]=(new \app\admin\model\AuthGroup())->insertGetId($group);
                    }
                    return  true;
                }catch (\Exception $e){
                    \think\Log::write("__________添加默认角色组错误____________");
                    \think\Log::write($e->getMessage());
                    return false;
                }

            }
        }
        return false;
    }


    /**
     * 同步前端用户
     * @param $user
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static  function synUser(&$user){
        $key = "syn_fa_user";
        $settingModel = new \app\admin\model\facrm\Setting();
        $row = $settingModel->where('key', $key)->cache($key)->find();
        if (!$row){
            \think\Log::write("同步未配置______sysdata_error","error");
            return false;
        }
        $values = json_decode($row['values'], true);//获取器不知道为什么失效了
        if (!isset($values['status']) || $values['status'] == 0){
            \think\Log::write("关闭同步了______sysdata_error","error");
            return false;//关闭同步了
        }

        $owner_user_ids = [];
        //如果选择了组、没有选择成员 自动分配客户
        if (!$values['owner_user_id'] && $values['group_id']) {

            $groupList = collection(\app\admin\model\AuthGroup::cache('FacrmAuthGroup')->select())->toArray();
            Tree::instance()->init($groupList);
            $groupIds = Tree::instance()->getChildrenIds($values['group_id'], true);
            $authGroupList = \app\admin\model\AuthGroupAccess::
            field('uid,group_id')
                ->where('group_id', 'in', $groupIds)
                ->select();
            foreach ($authGroupList as $k => $v) {
                if (in_array($v['uid'], $owner_user_ids)) continue;
                $owner_user_ids[] = $v['uid'];
            }

        } else {
            $owner_user_ids = explode(',', $values['owner_user_id']);
        }
        //添加
        $owner_user_id = $owner_user_ids ? $owner_user_ids[mt_rand(0, count($owner_user_ids) - 1)] : 0;
        $add_data = [
            'name' => $user['nickname'],
            'mobile' => $user['mobile'],
            'tags' => __('注册用户'),
            'telephone' => '',
            'source' => $values['source'],
            'create_user_id' => 0,
            'owner_user_id' => $owner_user_id,
            'province' => 0,
            'city' => 0,
            'area' => 0,
            'next_time' => $values['needfollow'] ? time() : 0,
            'follow_time' => time(),
            'collect_time' => time(),
            'user_id' => $user->id,
            'remark' => __("前台注册"),
        ];

        $result = false;
        Db::startTrans();
        try {
            if (isset($values['purpose'])&&$values['purpose']==2){
                //同步到线索
                $cModel = new \app\admin\model\facrm\Clues();
            }else{
                //同步到客户
                $cModel = new \app\admin\model\facrm\Customer();
            }

            $result = $cModel->add($add_data, 0, $owner_user_id,false);//不校验数据
            Db::commit();
        } catch (ValidateException $e) {
            \think\Log::write($e->getMessage()."_________sysdata_error");
            Db::rollback();

        } catch (PDOException $e) {
            \think\Log::write($e->getMessage()."_________sysdata_error");
            Db::rollback();
        } catch (Exception $e) {
            \think\Log::write($e->getMessage()."_________sysdata_error");

            Db::rollback();

        }
        return $result;
    }


    /**
     * 最近时间转换
     * @param $time
     * @return false|string
     */
    public static function timeTran($time)
    {

        $text = '';

        if (!$time) {
            return $text;
        }
        $current = time();
        $t = $current - $time;
        $retArr = array('刚刚', '秒前', '分钟前', '小时前', '天前', '月前', '年前');
        switch ($t) {
            case $t < 0://时间大于当前时间，返回格式化时间
                $text = date('Y-m-d', $time);
                break;
            case $t == 0://刚刚
                $text = $retArr[0];
                break;
            case $t < 60:// 几秒前
                $text = $t . $retArr[1];
                break;
            case $t < 3600://几分钟前
                $text = floor($t / 60) . $retArr[2];
                break;
            case $t < 86400://几小时前
                $text = floor($t / 3600) . $retArr[3];
                break;
            case $t < 2592000: //几天前
                $text = floor($t / 86400) . $retArr[4];
                break;
            case $t < 31536000: //几个月前
                $text = floor($t / 2592000) . $retArr[5];
                break;
            default : //几年前
                $text = floor($t / 31536000) . $retArr[6];
        }
        return $text;


    }



}